package com.oscar.ehome.view.setview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.oscar.ehome.R;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.messageBean.MessageListBean;
import com.oscar.ehome.bean.messageBean.MessagesBean;
import com.oscar.ehome.presenter.SetPresenter;
import com.oscar.ehome.utils.pullrefresh.PullToRefreshBase;
import com.oscar.ehome.utils.pullrefresh.PullToRefreshListView;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.view.MyList;
import com.oscar.ehome.utils.view.progressview.ProgressFrameLayout;
import com.oscar.ehome.utils.xrefresh.XRefreshView;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.messageview.MessageDetilActivity;
import com.oscar.ehome.view.messageview.view.MessageListView;
import com.oscar.ehome.view.setview.adapter.MyIssuesAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by juxing
 * author: MengWanhe
 * date: On 2017/7/21
 * 我的发布页
 */

public class MyfabuActivity extends BasesActivity<MessageListView, SetPresenter> implements XRefreshView.XRefreshViewListener,
        AdapterView.OnItemClickListener, MessageListView, AdapterView.OnItemLongClickListener, ProgressFrameLayout.AgainRequestListener {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /***
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * list view
     */
    @BindView(R.id.issueses_listview)
    MyList issuesesListview;
    /**
     * 无网络布局
     */
    @BindView(R.id.fabu_fragment)
    ProgressFrameLayout fabuFragment;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    @BindView(R.id.message_refview)
    XRefreshView messageRefview;
    MyIssuesAdapter adapter;

    SetPresenter messagePreaenter;
    private List<MessageListBean> lists = new ArrayList<MessageListBean>();
    private PopupWindow popupWindow;
    int longpostion = 0;//长按删除的条目

    String token = "";
    String id = "";
    private int page = 1;//页数
    private int page_size = 20;//每页的条数
    int size = 0;
    int count = 0;//条数
    public static long lastRefreshTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mafabu);
        ButterKnife.bind(this);
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(MyfabuActivity.this).getSystemConfig().getColor()));
        initView();
        initData();
        onClick();
    }

    @Override
    protected SetPresenter createPresenter() {
        messagePreaenter = new SetPresenter(this);
        return messagePreaenter;
    }

    /**
     * 判断是否有网
     */
    public boolean isNetWork() {
        boolean netWork = true;
        if (!CommonUtils.isNetConn(MyfabuActivity.this)) {
            netWork = false;
            return netWork;
        }
        return netWork;
    }

    /**
     * 初始化数据
     */
    public void initView() {
        titleImgBack.setImageResource(R.mipmap.fanhui);
        titleImgBack.setVisibility(View.VISIBLE);
        titleTopbar.setText("我的发布");
        token = SystemConfigFactory.getInstance(MyfabuActivity.this).getSystemConfig().getToken();

        adapter = new MyIssuesAdapter(MyfabuActivity.this, lists);
        issuesesListview.setAdapter(adapter);
    }

    /**
     * 点击事件
     */
    public void onClick() {
        messageRefview.setXRefreshViewListener(this);

        issuesesListview.setOnItemClickListener(this);
        issuesesListview.setOnItemLongClickListener(this);
        fabuFragment.setAgainRequestListener(this);
        // 设置是否可以下拉刷新
        messageRefview.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        messageRefview.setPullLoadEnable(false);
        // 设置上次刷新的时间
        messageRefview.restoreLastRefreshTime(lastRefreshTime);
        //当下拉刷新被禁用时，调用这个方法并传入false可以不让头部被下拉
        messageRefview.setMoveHeadWhenDisablePullRefresh(true);
        // 设置时候可以自动刷新
        messageRefview.setAutoRefresh(false);
    }

    /**
     * 请求数据
     */
    public void initData() {
        if (isNetWork()) {
            fabuFragment.stopRefresh();
            issuesesListview.setVisibility(View.VISIBLE);
            messagePreaenter.issuseMessage(token);
            showLoading();
        } else {
            fabuFragment.setVisibility(View.VISIBLE);
            fabuFragment.setLoadFail();
            issuesesListview.setVisibility(View.GONE);
        }
    }

    /**
     * 删除请求数据
     */
    public void DeleteData() {
        messagePreaenter.deleteIssuseMessage(token, id);
        showLoading();
    }

    @OnClick(R.id.title_layout_left)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String ids = lists.get(position).getId();
        String type = lists.get(position).getType();
        Intent intent = new Intent(this, MessageDetilActivity.class);
        intent.putExtra("ids", ids);
        intent.putExtra("type", type);
        startActivity(intent);
    }



    @Override
    public void getMessageList(MessagesBean result) {
        dismissLoading();
        messageRefview.stopRefresh();

        if (result != null) {
            fabuFragment.stopRefresh();
            issuesesListview.setVisibility(View.VISIBLE);
            if (page == 1) {
                lists.clear(); // 将原有的内容清空
            }
            lists = result.getList();
            count = result.getCount();
            size = lists.size();
            if (size < page_size && lists.size() > 0) {
                messageRefview.stopLoadMore();
            }
            if (size == 0) {
                fabuFragment.setNoResult();
                issuesesListview.setVisibility(View.GONE);
            }
            adapter.setLists(lists);
        } else {
            fabuFragment.setNoResult();
            issuesesListview.setVisibility(View.GONE);
        }
    }

    @Override
    public void deleteMessageList(String result) {
        dismissLoading();
        lists.remove(longpostion);
        adapter.setLists(lists);
        ToastUtil.show(MyfabuActivity.this, result);
    }

    @Override
    public void erroy() {
        dismissLoading();
        messageRefview.stopRefresh();
        fabuFragment.setNoResult();
        issuesesListview.setVisibility(View.GONE);
        ToastUtil.show(MyfabuActivity.this, getString(R.string.erry));
    }

    @Override
    public void erry(String result) {
        dismissLoading();
        messageRefview.stopRefresh();
        ToastUtil.show(this, result);
        fabuFragment.setNoResult();
        issuesesListview.setVisibility(View.GONE);
        if (result.contains("过期")) {
            this.getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        longpostion = position;
        if (null == popupWindow) {
            View popView = getLayoutInflater().inflate(R.layout.layout_long_click_dialog, null);
            RelativeLayout tvDelte = (RelativeLayout) popView.findViewById(R.id.tv_delete);
            tvDelte.setOnClickListener(clickListener);
            popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            popupWindow.setAnimationStyle(R.style.PopAnimStyle);
            popupWindow.setOutsideTouchable(true);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
        }
        if (popupWindow.isShowing())
            popupWindow.dismiss();
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        //展示位置：
        //参照点为view的右上角，偏移值为：x方向距离参照view的一定倍数距离
        //垂直方向自身减去popup自身高度的一半（确保在中间）
        popupWindow.showAtLocation(view, Gravity.TOP, 0,
                location[1] - CommonUtils.dipToPx(MyfabuActivity.this, 10f));
//        popupWindow.showAtLocation(view, Gravity.TOP, 0, location[1] - view.getHeight());
        return true;
    }

    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            id = lists.get(longpostion).getId();
            DeleteData();
            popupWindow.dismiss();
        }
    };

    @Override
    public void againRequest() {
        if (isNetWork()) {
            initData();
        } else {
            ToastUtil.show(MyfabuActivity.this, R.string.pull_to_refresh_network_error);
        }
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onRefresh(boolean isPullDown) {
        lastRefreshTime = messageRefview.getLastRefreshTime();
        messageRefview.restoreLastRefreshTime(lastRefreshTime);
        page = 1;
        initData();
    }

    @Override
    public void onLoadMore(boolean isSilence) {
        page++;
        initData();
    }

    @Override
    public void onRelease(float direction) {

    }

    @Override
    public void onHeaderMove(double headerMovePercent, int offsetY) {

    }
}
